#include "watchdog/WatchdogClientAgent.h"
#include "watchdog/Protocol.h"
#include "watchdog/SyncStatusTask.h"

#include "common/log/log.h"
#include "common/comm/TaskManager.h"

#include <iostream>
using namespace std;

WatchdogClientAgent::WatchdogClientAgent(){}
WatchdogClientAgent::WatchdogClientAgent(const SocketAddress &addr):TCPAgent(addr){}
WatchdogClientAgent::WatchdogClientAgent(const TCPSocket &sock, const SocketAddress &addr):TCPAgent(sock,addr){}

WatchdogClientAgent::~WatchdogClientAgent(){}

void WatchdogClientAgent::readBack(InReq &req ){
    cout << req.m_msgHeader.cmd << endl;
    cout << req.m_msgHeader.para1 << endl;

    string data(req.ioBuf, req.m_msgHeader.length);
    cout << data << endl;
    SyncStatusTask *pTask = TaskManager::getInstance()->create<SyncStatusTask>();
    pTask->setData(data);
    pTask->goNext();

    MsgHeader msg;
    msg.cmd = req.m_msgHeader.cmd;
    msg.length = req.m_msgHeader.length;
    msg.para1 = req.m_msgHeader.para1;
    sendPackage(msg, data.c_str());
    data.clear();
}
void WatchdogClientAgent::writeBack( bool result){

}
int WatchdogClientAgent::sendPackage(MsgHeader &header, const char *dataStr){
    uint32_t msgLength = header.length + sizeof(MsgHeader);
    char *sendBuf = new char[msgLength + 1];
    memset(sendBuf, 0, msgLength + 1);
    memcpy(sendBuf, &header, sizeof(MsgHeader));
    if (dataStr != NULL){
        memcpy(sendBuf + sizeof(MsgHeader), dataStr, header.length);
    }

    if (this->writeToBuffer(sendBuf, msgLength) == FAILED){
        return FAILED;
    }

    return SUCCESSFUL;
}

void WatchdogClientAgent::recycler(){
    // 只有epoll退出之前才调用
    cout << getID() << " agent deleted" << endl;
}

